<template>
  <div class="auth-test-page">
    <el-card class="test-card">
      <template #header>
        <div class="card-header">
          <span>JWT认证功能测试</span>
          <el-button type="primary" @click="refreshStatus">刷新状态</el-button>
        </div>
      </template>
      
      <!-- 认证状态显示 -->
      <div class="status-section">
        <h3>当前认证状态</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="认证状态">
            <el-tag :type="authStatus.isAuthenticated ? 'success' : 'danger'">
              {{ authStatus.isAuthenticated ? '已认证' : '未认证' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="Token状态">
            <el-tag :type="authStatus.hasToken ? 'success' : 'warning'">
              {{ authStatus.hasToken ? '存在' : '不存在' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="Token过期">
            <el-tag :type="authStatus.isExpired ? 'danger' : 'success'">
              {{ authStatus.isExpired ? '已过期' : '有效' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="用户信息">
            <span>{{ authStatus.user ? authStatus.user.username : '无' }}</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 测试按钮组 -->
      <div class="test-section">
        <h3>功能测试</h3>
        <div class="test-buttons">
          <el-button type="primary" @click="testValidRequest" :loading="loading.validRequest">
            测试有效请求
          </el-button>
          <el-button type="warning" @click="testExpiredToken" :loading="loading.expiredToken">
            模拟Token过期
          </el-button>
          <el-button type="danger" @click="testInvalidToken" :loading="loading.invalidToken">
            模拟无效Token
          </el-button>
          <el-button type="info" @click="testNoToken" :loading="loading.noToken">
            测试无Token请求
          </el-button>
          <el-button type="success" @click="testDashboardAPI" :loading="loading.dashboardAPI">
            测试Dashboard API
          </el-button>
          <el-button type="primary" @click="testCustomScanAPI" :loading="loading.customScanAPI">
            测试CustomScan API
          </el-button>
        </div>
      </div>

      <!-- 测试结果显示 -->
      <div class="result-section" v-if="testResults.length > 0">
        <h3>测试结果</h3>
        <div class="results-container">
          <div 
            v-for="(result, index) in testResults" 
            :key="index" 
            class="result-item"
            :class="result.success ? 'success' : 'error'"
          >
            <div class="result-header">
              <span class="result-title">{{ result.title }}</span>
              <span class="result-time">{{ formatTime(result.timestamp) }}</span>
            </div>
            <div class="result-content">
              <p><strong>状态:</strong> {{ result.success ? '成功' : '失败' }}</p>
              <p><strong>消息:</strong> {{ result.message }}</p>
              <p v-if="result.details"><strong>详情:</strong> {{ result.details }}</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="action-section">
        <el-button type="danger" @click="clearAuth">清除认证信息</el-button>
        <el-button type="info" @click="clearResults">清除测试结果</el-button>
        <el-button type="primary" @click="goToLogin">前往登录</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { auth } from '@/utils/auth'
import authApi from '@/api/auth'
import dashboardApi from '@/api/dashboard'
import customScanApi from '@/api/customScan'

const router = useRouter()

// 响应式数据
const authStatus = ref({
  isAuthenticated: false,
  hasToken: false,
  isExpired: false,
  user: null
})

const loading = ref({
  validRequest: false,
  expiredToken: false,
  invalidToken: false,
  noToken: false,
  dashboardAPI: false,
  customScanAPI: false
})

const testResults = ref([])

// 刷新认证状态
const refreshStatus = () => {
  const token = auth.getToken()
  const user = auth.getUser()
  
  authStatus.value = {
    isAuthenticated: auth.isAuthenticated(),
    hasToken: !!token,
    isExpired: token ? auth.isTokenExpired(token) : false,
    user: user
  }
}

// 添加测试结果
const addTestResult = (title, success, message, details = null) => {
  testResults.value.unshift({
    title,
    success,
    message,
    details,
    timestamp: new Date()
  })
  
  // 限制结果数量
  if (testResults.value.length > 10) {
    testResults.value = testResults.value.slice(0, 10)
  }
}

// 测试有效请求
const testValidRequest = async () => {
  loading.value.validRequest = true
  try {
    const response = await authApi.getProfile()
    addTestResult('有效请求测试', true, '请求成功', JSON.stringify(response))
    ElMessage.success('有效请求测试成功')
  } catch (error) {
    addTestResult('有效请求测试', false, error.message, JSON.stringify(error))
    ElMessage.error('有效请求测试失败: ' + error.message)
  } finally {
    loading.value.validRequest = false
  }
}

// 模拟Token过期
const testExpiredToken = async () => {
  loading.value.expiredToken = true
  try {
    // 设置一个过期的Token
    const expiredToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ0ZXN0IiwibmFtZSI6InRlc3QiLCJpYXQiOjE1MTYyMzkwMjIsImV4cCI6MTUxNjIzOTAyMn0.invalid'
    localStorage.setItem('token', expiredToken)
    
    const response = await authApi.getProfile()
    addTestResult('过期Token测试', false, '应该失败但成功了', JSON.stringify(response))
    ElMessage.warning('过期Token测试异常：请求成功了')
  } catch (error) {
    addTestResult('过期Token测试', true, '正确拦截了过期Token', error.message)
    ElMessage.success('过期Token测试成功：正确拦截')
  } finally {
    loading.value.expiredToken = false
    refreshStatus()
  }
}

// 模拟无效Token
const testInvalidToken = async () => {
  loading.value.invalidToken = true
  try {
    // 设置一个无效的Token
    localStorage.setItem('token', 'invalid.token.here')
    
    const response = await authApi.getProfile()
    addTestResult('无效Token测试', false, '应该失败但成功了', JSON.stringify(response))
    ElMessage.warning('无效Token测试异常：请求成功了')
  } catch (error) {
    addTestResult('无效Token测试', true, '正确拦截了无效Token', error.message)
    ElMessage.success('无效Token测试成功：正确拦截')
  } finally {
    loading.value.invalidToken = false
    refreshStatus()
  }
}

// 测试无Token请求
const testNoToken = async () => {
  loading.value.noToken = true
  try {
    // 临时移除Token
    const originalToken = localStorage.getItem('token')
    localStorage.removeItem('token')
    
    const response = await authApi.getProfile()
    addTestResult('无Token测试', false, '应该失败但成功了', JSON.stringify(response))
    ElMessage.warning('无Token测试异常：请求成功了')
    
    // 恢复Token
    if (originalToken) {
      localStorage.setItem('token', originalToken)
    }
  } catch (error) {
    addTestResult('无Token测试', true, '正确拦截了无Token请求', error.message)
    ElMessage.success('无Token测试成功：正确拦截')
    
    // 恢复Token
    const originalToken = auth.getToken()
    if (!originalToken) {
      // 如果没有原始Token，需要重新获取
      refreshStatus()
    }
  } finally {
    loading.value.noToken = false
    refreshStatus()
  }
}

// 测试Dashboard API
const testDashboardAPI = async () => {
  loading.value.dashboardAPI = true
  try {
    const response = await dashboardApi.getDashboardDetail()
    addTestResult('Dashboard API测试', true, 'Dashboard API请求成功', JSON.stringify(response))
    ElMessage.success('Dashboard API测试成功')
  } catch (error) {
    addTestResult('Dashboard API测试', false, error.message, JSON.stringify(error))
    ElMessage.error('Dashboard API测试失败: ' + error.message)
  } finally {
    loading.value.dashboardAPI = false
  }
}

// 测试CustomScan API
const testCustomScanAPI = async () => {
  loading.value.customScanAPI = true
  try {
    const response = await customScanApi.getTasks()
    addTestResult('CustomScan API测试', true, 'CustomScan API请求成功', JSON.stringify(response))
    ElMessage.success('CustomScan API测试成功')
  } catch (error) {
    addTestResult('CustomScan API测试', false, error.message, JSON.stringify(error))
    ElMessage.error('CustomScan API测试失败: ' + error.message)
  } finally {
    loading.value.customScanAPI = false
  }
}

// 清除认证信息
const clearAuth = () => {
  auth.clearAuth()
  refreshStatus()
  addTestResult('清除认证', true, '已清除所有认证信息')
  ElMessage.success('认证信息已清除')
}

// 清除测试结果
const clearResults = () => {
  testResults.value = []
  ElMessage.success('测试结果已清除')
}

// 前往登录
const goToLogin = () => {
  router.push('/login')
}

// 格式化时间
const formatTime = (date) => {
  return date.toLocaleString('zh-CN')
}

// 组件挂载时刷新状态
onMounted(() => {
  refreshStatus()
})
</script>

<style scoped>
.auth-test-page {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.test-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.status-section,
.test-section,
.result-section,
.action-section {
  margin-bottom: 30px;
}

.test-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.results-container {
  max-height: 400px;
  overflow-y: auto;
}

.result-item {
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 15px;
  margin-bottom: 10px;
}

.result-item.success {
  border-color: #67c23a;
  background-color: #f0f9ff;
}

.result-item.error {
  border-color: #f56c6c;
  background-color: #fef0f0;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.result-title {
  font-weight: bold;
  font-size: 16px;
}

.result-time {
  color: #909399;
  font-size: 12px;
}

.result-content p {
  margin: 5px 0;
  word-break: break-all;
}
</style> 